package com.zzyl.nursing.service.impl;

import java.util.HashMap;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.UUID;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-26
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {

    @Autowired
    private WechatServiceImpl wechatService;
    @Autowired
    private TokenService tokenService;

    /**
     * 微信小程序用户登录
     *
     * @param userLoginRequestDto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        // 1. 获取OpenID
        String openId = wechatService.getOpenid(userLoginRequestDto.getCode());

        // 2.根据openid查询用户信息判断用户是否存在 flag 用于区别是否新增用户
        boolean flag = false;
        FamilyMember familyMember = this.lambdaQuery().eq(FamilyMember::getOpenId, openId).one();
        if (ObjectUtil.isEmpty(familyMember)) {
            // 2.1 如果不存在，则新增用户信息
            familyMember = FamilyMember.builder().openId(openId).build();
            // flag 为 true 表示新增用户
            flag = true;
        }

        // 3.获取手机号
        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());

        // 4.新增或者修改用户信息
        if (flag) {
            // 4.1 新增用户信息
            familyMember.setPhone(phone);
            familyMember.setName(UUID.randomUUID().toString());
            this.save(familyMember);
        }else {
            // 4.2 查询用户手机号是否变更
            String userPhone = this.lambdaQuery().eq(FamilyMember::getOpenId, openId).one().getPhone();
            if (!StrUtil.equals(familyMember.getPhone(), userPhone)) {
                // 4.3 如果变更，则更新用户信息
                familyMember.setPhone(phone);
                this.updateById(familyMember);
            }
        }


        // 5.把用户ID和昵称封装到token
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("nickName", familyMember.getName());
        String token = tokenService.createToken(claims);

        // 6.返回数据
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());
        return loginVo;

    }
}
